package com.rk.security;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;

import com.rk.service.LoginService;

public class AuthenticationFailureHandlerBean extends SimpleUrlAuthenticationFailureHandler {

	private String defaultFailureUrl ="/loginfailed";
	private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
	
	private LoginService service;
    
    public LoginService getService() {
    	return service;
    }

    public void setService(LoginService service) {
	this.service = service;
	}
    
	@Override
	public void onAuthenticationFailure(HttpServletRequest request,
			HttpServletResponse response, AuthenticationException exception)
			throws IOException, ServletException {

		String username = request.getParameter("j_username").trim();
		HttpSession session = request.getSession();

		// Here you can add some custom functionality

		if (exception instanceof DisabledException) {
			session.setAttribute("SPRING_SECURITY_LOGIN_ERROR_TYPE", "2");
		} else if (exception instanceof BadCredentialsException) {

			session.setAttribute("SPRING_SECURITY_LOGIN_ERROR_TYPE", "2");
			/*
			 * if( false == service.getLoginLockedStatus(username)){
			 * session.setAttribute("SPRING_SECURITY_LOGIN_ERROR_TYPE", "2");
			 * }else{ session.setAttribute("SPRING_SECURITY_LOGIN_ERROR_TYPE",
			 * "1"); }
			 */
		} else {
			session.setAttribute("SPRING_SECURITY_LOGIN_ERROR_TYPE", "1");
		}
		session.setAttribute("SPRING_SECURITY_LAST_USERNAME", username);

		if (isUseForward()) {
			request.getRequestDispatcher(defaultFailureUrl).forward(request, response);
		} else {
			redirectStrategy.sendRedirect(request, response, defaultFailureUrl);
		}

	}

	@Override
	public void setDefaultFailureUrl(String defaultFailureUrl) {
		this.defaultFailureUrl = defaultFailureUrl;
		super.setDefaultFailureUrl(defaultFailureUrl);
	}

}
